'use strict';
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ' + event)
  
  //获得数据库实例，并获取表
  let db = uniCloud.database();
  let db_checkin = db.collection('db_checkin');
  
  const { code } = event;
  //通过code换取微信openid
  let code2session = await uniCloud.httpclient.request("https://api.weixin.qq.com/sns/jscode2session?appid=wx9d8fff4d99ca6c9c&secret=7f4b16a0cfe7d6cf7d101e703ba8d1e3&js_code="+code+"&grant_type=authorization_code",{dataType:"json"});
  let openid = code2session.data.openid;
  
  let myquery = await db_checkin.where({
    openid: openid
  }).get();
  
  let today_zero=new Date(new Date().toLocaleDateString()).getTime();
  let now=new Date().getTime();
  
  if(myquery.data.length>0){
	  let query_data=myquery.data[0];
	  if(query_data.checkintime>today_zero){
		  return false;
	  }else{
		  await db_checkin.where({
			  openid:openid
		  }).update({
			  checkintime:now
		  });
		  return true;
	  }
  }else{
	  await db_checkin.add({
		  openid:openid,
		  checkintime:now
	  });
	  return true;
  }
};
